package za.co.trojanc.ini_lib;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * A class used to save an <code>INIConfig</code> object to an ini file.
 * @author Charl Thiem
 * @since 09 Sep 2009
 */
public class INIWriter {

	/** File to which configuration should be written */
	private File iniFile;
	
	/** Flag if the comments and whitespace should be written */
	private boolean writeComments = false;
	
	/**
	 * Creates a new instance of <code>INIWriter</code>.
	 * @param file File to write to.
	 */
	public INIWriter(File file) {
		this.iniFile = file;
	}

	/**
	 * Creates a new instance of <code>INIWriter</code>.
	 * @param filePath String representing the path to the file.
	 */
	public INIWriter(String filePath) {
		this(new File(filePath));
	}
	
	public void writeConfig(INIConfig config) throws IOException{
		/* Writer that will perform the output */
		PrintWriter out = new PrintWriter(this.iniFile);
		for (INISection section : config.getSections()) {
			if (this.writeComments && section.getPreText() != null) {
				/*
				 * Write comments if required
				 */
				out.println(section.getPreText());
			}
			
			/*
			 * Write section tag
			 */
			out.println(new StringBuilder().append("[").append(section.getName()).append("]").toString());
			
			for (INIField field : section.getFields()) {
				
				if (this.writeComments && field.getPreText() != null) {
					/*
					 * Write comments if required
					 */
					out.println(section.getPreText());
				}
				/*
				 * Write key=>value line
				 */
				String value = field.getValue();
				if (value == null) {
					value = "";
				}
				else {
					value = value.replaceAll("\n", "<br>");
				}
				out.println(new StringBuilder().append(field.getName()).append("=").append(value).toString());
			}
		}
		
		out.close();
	}
	
	
	
	/**
	 * Sets if comments should be written into configuration file.
	 * @param flag True if comments should be written.
	 */
	public void setWriteComments(boolean flag) {
		this.writeComments = flag;
	}
}
